/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.SOP;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import merlion.common.util.Consts;
import merlion.common.util.exception.NotExistException;
import merlion.crm.slcm.entity.Customer;
import merlion.crm.slcm.session.SLCSessionBeanLocal;
import merlion.crm.sopm.entity.PurchaseOrder;
import merlion.crm.sopm.entity.SalesOrder;
import merlion.crm.sopm.session.SOPSessionBeanLocal;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import managedbean.Workspace.FileUploadManagerBean;
import managedbean.Workspace.JobManagerBean;
import merlion.crm.slcm.entity.ContactRecord;
import merlion.crm.sopm.entity.ItemLine;
import merlion.frm.bpm.session.SalesBPSessionBeanLocal;
import merlion.frm.ccm.session.CCSessionBeanLocal;
import merlion.mrp.atpm.session.ATPSessionBeanLocal;
import merlion.mrp.ppm.session.MPSPlanningSessionLocal;
import merlion.scm.icm.session.InventoryControlSessionBeanLocal;
import merlion.scm.lcm.entity.DeliveryOrder;
import merlion.scm.lcm.session.LogisticControlSessionBeanLocal;

/**
 *
 * @author Yuwei
 */
@ManagedBean(name = "soManagerBean")
@ViewScoped
public class SalesOrderManagerBean {

    public static final String SO = "SO";
    public static final String RESULT1 = "RESULT1";
    public static final String CUR = "CUR";
    public static final String PAYMODE = "PAYMODE";
    @EJB
    private SOPSessionBeanLocal sOPSessionBean;
    @EJB
    private SLCSessionBeanLocal sLCSessionBean;
    @EJB
    private CCSessionBeanLocal ccSessionBean;
    @EJB
    private ATPSessionBeanLocal atpSessionBean;
    @EJB
    private SalesBPSessionBeanLocal sbpSessionBean;
    @EJB
    private InventoryControlSessionBeanLocal icSessionBean;
    @EJB
    private MPSPlanningSessionLocal mpspSessionBean;
    @EJB
    private LogisticControlSessionBeanLocal lcSessionBean;
    @ManagedProperty(value = "#{fileUploadManagerBean}")
    private FileUploadManagerBean fileManagerBean;
    private SalesOrder salesOrder;
    private PurchaseOrder purchaseOrder;
    private Customer customer;
    private String poNumStr;
    private String salesOrderIdStr;
    private String result;
    private String errorMsg;
    private String currency;
    private String paymentMode;
    private DeliveryOrder do1;
    private DeliveryOrder do2;
    private Date date1;
    private Date date2;
    private Map<String, String> statuses = new HashMap<String, String>();
    @ManagedProperty(value = "#{jobManagerBean}")
    private JobManagerBean jobManager;
    private static final SimpleDateFormat formatter = new SimpleDateFormat("MMMMM dd, yyyy");

    /** Creates a new instance of SalesOrderManagerBean */
    public SalesOrderManagerBean() {

        statuses.put("Initiated", "Initiated");
        statuses.put("Waiting for Cash in Advance Payment", "Waiting for Cash in Advance Payment");
        statuses.put("Credit Check Failed", "Credit Check Failed");
        statuses.put("ATPChecking", "ATPChecking");
        statuses.put("ATPPending", "ATPPENDING");
        statuses.put("Order Fulfilling", "Order Fulfilling");
        statuses.put("Order Shipped", "Order Shipped");
        statuses.put("Order Cancelled", "Order Cancelled");
        statuses.put("Order Blocked (default)", "Order Blocked (default)");

    }

    @PostConstruct
    public void init() {
        salesOrder = (SalesOrder) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(SO);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(SO);
        if (salesOrder == null) {
            salesOrder = new SalesOrder();
            salesOrder.setSalesOrderIdStr(sOPSessionBean.generateSalesOrderId());
        }

        ArrayList<DeliveryOrder> list = new ArrayList<DeliveryOrder>(salesOrder.getDeliveryOrders());
        if (list.size() > 0) {
            do1 = list.get(0);
        }
        if (list.size() > 1) {
            do2 = list.get(1);
        }
    }

    public String createSalesOrder() {
        try {
            purchaseOrder = sOPSessionBean.getPurchaseOrderById(purchaseOrder.getPoNumber());
            if (purchaseOrder.getSalesOrder() != null) {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "There already exists a sales order based on the purchase order", "There already exists a sales order based on the purchase order"));
                return null;
            }
            salesOrder.setPurchaseOrder(purchaseOrder);
            salesOrder.setPromotion(purchaseOrder.getSalesQuotation().getPromotion());
            salesOrder.setCustomer(purchaseOrder.getCustomer());
            salesOrder.setDeliveryOrders(purchaseOrder.getDeliveryOrders());
            salesOrder.setSalesOrderStatus(Consts.ORDER_INITIATED);
            salesOrder.setSubtotal(purchaseOrder.getSubtotal());
            salesOrder.setTax(purchaseOrder.getTax());
            salesOrder.setTotal(purchaseOrder.getTotal());
            salesOrder.setFreightOnBoard(purchaseOrder.getFreightOnBoard());
            salesOrder.setFullShipment(purchaseOrder.getFullShipment());
            salesOrder.setPaymentMode(purchaseOrder.getPaymentMode());
            salesOrder.setCurrency(purchaseOrder.getCurrency());
            purchaseOrder.setSalesOrder(salesOrder);
            salesOrder.setComments(purchaseOrder.getComments());
            salesOrder.setItemLines(purchaseOrder.getItemLines());
            salesOrder.setMemberDiscount(purchaseOrder.getMemberDiscount());
            salesOrder.setOrderDiscount(purchaseOrder.getOrderDiscount());
            salesOrder.setSpecialDiscount(purchaseOrder.getSpecialDiscount());
            ArrayList<DeliveryOrder> dList = new ArrayList<DeliveryOrder>(purchaseOrder.getDeliveryOrders());
            int i = 0;
            for (DeliveryOrder d : salesOrder.getDeliveryOrders()) {
                d.setIndicativeLeadTimeTS(dList.get(i).getLeadTimeTS());
                d.setIndicativeLeadTime(dList.get(i).getLeadTime());
                d.setSalesOrder(salesOrder);
                d.setStatus(Consts.LOGISTIC_DELIVERYORDER_QUEUING);
                i++;
            }
        } catch (NotExistException ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Could not find Purchase Order", "Could not find Purchase Order"));
            return null;
//            errorMsg = "Could not find Purchase Order with PO Number " + poNumStr + "!!!!";
//            return "displaySOError";
        }
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(SO, salesOrder);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(CUR, currency);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(PAYMODE, paymentMode);

        return "createSalesOrderConfirm?faces-redirect=true";
    }

    public String persistSalesOrder() {

        // Set requested lead time
        
        long eightHours = (long) (8 * 60 * 60 * 1000);
        if (date1 != null) {
            do1.setIndicativeLeadTimeTS(new Timestamp(date1.getTime() + eightHours));
            do1.setIndicativeLeadTime(formatter.format(do1.getLeadTimeTS()));
            System.out.println("Date 1: " + date1.toString() + " " + do1.getIndicativeLeadTimeTS().toString());
        }
        if (date2 != null && do2 != null) {
            do2.setIndicativeLeadTimeTS(new Timestamp(date2.getTime() + eightHours));
            do2.setIndicativeLeadTime(formatter.format(do2.getLeadTimeTS()));
            System.out.println("Date 2: " + date2.toString() + " " + do2.getIndicativeLeadTimeTS().toString());
        }

        salesOrder.setDeliveryOrders(new ArrayList<DeliveryOrder>());
        salesOrder.getDeliveryOrders().add(do1);
        if (do2 != null) {
            salesOrder.getDeliveryOrders().add(do2);
        }

        salesOrder = sOPSessionBean.saveSalesOrder(salesOrder);
        if (salesOrder != null) {
            result = "Sales Order " + salesOrder.getSalesOrderIdStr() + " saved successfully.";
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(RESULT1, result);
            if (salesOrder.getPaymentMode().booleanValue() == Boolean.TRUE && !salesOrder.getSalesOrderStatus().equals(Consts.ORDER_WAITING_CONFIRMATION)) {
                //Pay By Cash In advance
                salesOrder.setSalesOrderStatus(Consts.ORDER_WAITFORCIA);
                sOPSessionBean.saveChangedSalesOrder(salesOrder);
                for (DeliveryOrder d : salesOrder.getDeliveryOrders()){
                   jobManager.assignJobInvoiceCIA(d.getId()); 
                }  

            } else if(!salesOrder.getSalesOrderStatus().equals(Consts.ORDER_WAITING_CONFIRMATION)) {//Credit Purchase
                //initiate credit check
                sOPSessionBean.saveChangedSalesOrder(salesOrder);
                boolean creditCheckResult = ccSessionBean.creditCheck(salesOrder);
                //Debugging
                System.out.println("Credit Check testing: customer credit limit: " + salesOrder.getCustomer().getCreditAccount().getCreditGroup().getCreditLimitForDs());
                System.out.println("Credit check testing: customer available credit to use: " + salesOrder.getCustomer().getCreditAccount().getCreditBalance());
                if (creditCheckResult == Boolean.FALSE) {
                    jobManager.addJobCC(salesOrder.getId());
                    salesOrder.setSalesOrderStatus(Consts.ORDER_CCFAILED);
                    sOPSessionBean.saveChangedSalesOrder(salesOrder);
                } else {
                    //Initiate ATP Check
                    sOPSessionBean.saveChangedSalesOrder(salesOrder);
                    ArrayList<DeliveryOrder> dList = new ArrayList<DeliveryOrder>(salesOrder.getDeliveryOrders());
                    for(DeliveryOrder d: dList){
                        atpSessionBean.getConfirmedLeadTime(d, d.getLeadTimeTS());      
                    }
                    try {
                        salesOrder = sOPSessionBean.getSalesOrderById(salesOrder.getSalesOrderIdStr());
                        jobManager.addJobATPSO(salesOrder.getId());
                        sOPSessionBean.saveChangedSalesOrder(salesOrder);
                    } catch (NotExistException ex) {
                        Logger.getLogger(SalesOrderManagerBean.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    
                }
            }

            return "viewSalesOrderStatus?faces-redirect=true";
        } else {
            errorMsg = "Sales Order didn't saved successfully";
            return "displaySOError?faces-redirect=true";
        }
    }

    public String cancelCreateSalesOrder() {
        result = "Create Sales Order cancelled and it has not been saved.";
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(RESULT1, result);
        return "viewSalesOrderStatus?faces-redirect=true";
    }

    public String populateSalesOrder() {
        try {
            salesOrder = sOPSessionBean.getSalesOrderById(salesOrder.getSalesOrderIdStr());
            boolean currencyBoolean = salesOrder.getCurrency();
            if (currencyBoolean == Boolean.TRUE) {
                currency = "SGD";
            } else {
                currency = "USD";
            }
            boolean paymentModeBoolean = salesOrder.getPaymentMode();
            if (paymentModeBoolean == Boolean.TRUE) {
                paymentMode = "CIA";
            } else {
                paymentMode = "PBC";
            }

            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(SO, salesOrder);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(CUR, currency);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(PAYMODE, paymentMode);

            return "viewSalesOrderDisplay";
        } catch (NotExistException nee) {
            errorMsg = "Could not find Sales Order with Id " + salesOrderIdStr + "!!!!";
            return "displaySOError?faces-redirect=true";
        }
    }

    public String updateSalesOrder() {
        if (salesOrder.getSalesOrderStatus().equals(Consts.ORDER_FULFILLING) || salesOrder.getSalesOrderStatus().equals(Consts.ORDER_BLOCKED)
                || salesOrder.getSalesOrderStatus().equals(Consts.ORDER_SHIPPED) || salesOrder.getSalesOrderStatus().equals(Consts.ORDER_CANCELLED)) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "You are not allowed to edit the sales order at this stage", "You are not allowed to edit the sales order at this stage"));
            return null;
        } else {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(SO, salesOrder);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(CUR, currency);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(PAYMODE, paymentMode);

            return "viewSalesOrderEdit?faces-redirect=true";
        }
    }
    
    public void aTPCheck1(ActionEvent event) {
      if(salesOrder.getSalesOrderStatus().equals(Consts.ORDER_WAITFORCIA) || salesOrder.getSalesOrderStatus().equals(Consts.ORDER_CCFAILED)){
         FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "You cannot do the ATP Check at this stage", "You cannot do the ATP Check at this stage"));
      }
      else{
      atpSessionBean.getConfirmedLeadTime(do1, new Timestamp(date1.getTime()));
      do1 = sbpSessionBean.getDeliveryOrderById(do1.getId());
      System.out.println("&&&*&^%$#@!#$%^$%^&&**&^%##########do1"+new Timestamp(date1.getTime()));
      System.out.println("&&&*&^%$#@!#$%^$%^&&**&^%##########do1"+do1.getLeadTime());
      }
    }
    
    public void aTPCheck2 (ActionEvent event) {
        if(salesOrder.getSalesOrderStatus().equals(Consts.ORDER_WAITFORCIA) || salesOrder.getSalesOrderStatus().equals(Consts.ORDER_CCFAILED)){
         FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "You cannot do the ATP Check at this stage", "You cannot do the ATP Check at this stage"));
      }
      else{
       atpSessionBean.getConfirmedLeadTime(do2, new Timestamp(date2.getTime()));
       do2 = sbpSessionBean.getDeliveryOrderById(do2.getId());
       System.out.println("&&&*&^%$#@!#$%^$%^&&**&^%##########do2"+do2.getIndicativeLeadTime());
       System.out.println("&&&*&^%$#@!#$%^$%^&&**&^%##########do2"+do2.getLeadTime());
        }
    }

    public String closeSalesOrder() {
        result = "Sales Order " + salesOrder.getSalesOrderIdStr() + " closed.";
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(RESULT1, result);
        return "viewSalesOrderStatus";
    }
    
    public String confirmFulfilSalesOrder(){
        if(salesOrder.getSalesOrderStatus().equals(Consts.ORDER_WAITING_CONFIRMATION)){
        //validation: Only both deliveryOrders' ATP check passed sales order can be confirmedList<DeliveryOrder> dos = (List<DeliveryOrder>) salesOrder.getDeliveryOrders();
//        List<DeliveryOrder> dos1 = (List<DeliveryOrder>) salesOrder.getDeliveryOrders();
//        for(int i = 0; i < dos1.size(); i++){
//            if(dos1.get(i).getLeadTime().equals("Pending")||dos1.get(i).getLeadTime().equals(Consts.ATP_SO_FAIL)){
//                FacesContext.getCurrentInstance().addMessage(null,
//                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Both delivery order need ATP check passes, in order to confirm sales order", "Both delivery order need ATP check passes, in order to confirm sales order"));
//                return null;
//            }
//        }
      
        //Confirm and start fulfilling sales order
        List<DeliveryOrder> dos = (List<DeliveryOrder>) salesOrder.getDeliveryOrders();
        for(int i = 0; i < dos.size(); i++){
            dos.get(i).setStatus(Consts.LOGISTIC_DELIVERYORDER_QUEUING);
        }      
        salesOrder.setSalesOrderStatus(Consts.ORDER_FULFILLING);
        sOPSessionBean.saveChangedSalesOrder(salesOrder);
        result = "Sales Order " + salesOrder.getSalesOrderIdStr() + " confirmed.";
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(RESULT1, result);
        return "viewSalesOrderStatus";
        }
        else {
             FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "You cannot confirm sales order at this stage", "You cannot confirm sales order at this stage"));
              return null;
        }
    }

    public String cancelSalesOrder() {
        System.out.println("cancel");
        
        //refund payment
        if(salesOrder.getPaymentMode().booleanValue() == Boolean.TRUE){
        //pay by cash in advance
        ArrayList<DeliveryOrder> dList = new ArrayList<DeliveryOrder>(salesOrder.getDeliveryOrders());
        for(DeliveryOrder d: dList){
            if(d.getInvoice()== null || d.getInvoice().getCustomerPaymentRecord() == null)
                break;
            else if(d.getInvoice().getCustomerPaymentRecord().getPaymentAmount()!=0.0)
                jobManager.assignJobRefundCIA(d.getId());
                //sbpSessionBean.refund(d);        
        }
        System.out.println("###################refund successfully!");
        }
        // unreserve inventory
        ArrayList<DeliveryOrder> dList1 = new ArrayList<DeliveryOrder>(salesOrder.getDeliveryOrders());
        for(DeliveryOrder d: dList1){
            ArrayList<ItemLine> iList = new ArrayList<ItemLine>(d.getItemLines());
            for(ItemLine i: iList){
               if(i.getReservations()!=null)
                   if(!icSessionBean.unreserveInventory(d.getId())) {
                       return "displaySOError";
                   }
                   else{
                      d = lcSessionBean.getDeliveryOrderById(d.getId());
                   }
                   break;
            }      
        }
        System.out.println("###################unreserve inventory successfully!");
        // unreserve planned production
       ArrayList<DeliveryOrder> dList2 = new ArrayList<DeliveryOrder>(salesOrder.getDeliveryOrders()); 
       for(DeliveryOrder d: dList2){
           if (!mpspSessionBean.unreservePlannedProduction(d)) {
               return "displaySOError";
           }
       }
       System.out.println("###################unreserve planned production successfully!");
       
       try { 
       salesOrder = sOPSessionBean.getSalesOrderById(salesOrder.getSalesOrderIdStr());
       }
       catch (Exception e) {
          return "displaySOError";
       }
       
        salesOrder.setCancelled(Boolean.TRUE);
        salesOrder.setSalesOrderStatus(Consts.ORDER_CANCELLED);
        String newStatus = sOPSessionBean.saveChangedSalesOrder(salesOrder);
       
        if (newStatus == null) {
            errorMsg = "An error has occurred. The Sales Order has not been changed.";
            return "displaySOError";
        }
        result = "Sales Order " + salesOrder.getSalesOrderIdStr() + " cancelled successfully.\nNew Status is: " + newStatus + "!";
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(RESULT1, result);
        return "viewSalesOrderStatus?faces-redirect=true";
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public String getPoNumStr() {
        return poNumStr;
    }

    public void setPoNumStr(String poNumStr) {
        this.poNumStr = poNumStr;
    }

    public PurchaseOrder getPurchaseOrder() {
        return purchaseOrder;
    }

    public void setPurchaseOrder(PurchaseOrder purchaseOrder) {
        this.purchaseOrder = purchaseOrder;
    }

    public SLCSessionBeanLocal getsLCSessionBean() {
        return sLCSessionBean;
    }

    public void setsLCSessionBean(SLCSessionBeanLocal sLCSessionBean) {
        this.sLCSessionBean = sLCSessionBean;
    }

    public SOPSessionBeanLocal getsOPSessionBean() {
        return sOPSessionBean;
    }

    public void setsOPSessionBean(SOPSessionBeanLocal sOPSessionBean) {
        this.sOPSessionBean = sOPSessionBean;
    }

    public SalesOrder getSalesOrder() {

        return salesOrder;
    }

    public void setSalesOrder(SalesOrder salesOrder) {
        this.salesOrder = salesOrder;
        this.salesOrderIdStr = salesOrder.getSalesOrderIdStr();
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public String getResult() {
        String r = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(RESULT1);
        if (r != null) {
            result = r;
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(RESULT1);
        }
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getSalesOrderIdStr() {
        return salesOrderIdStr;
    }

    public void setSalesOrderIdStr(String salesOrderIdStr) {
        this.salesOrderIdStr = salesOrderIdStr;
    }

    public String getCurrency() {
        String cur = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(CUR);
        if (cur != null) {
            currency = cur;
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(CUR);
        }
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public String getPaymentMode() {
        String paymode = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(PAYMODE);
        if (paymode != null) {
            paymentMode = paymode;
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(PAYMODE);
        }
        return paymentMode;
    }

    public void setPaymentMode(String paymentMode) {
        this.paymentMode = paymentMode;
    }

    public Map<String, String> getStatuses() {
        return statuses;
    }

    public void setStatuses(Map<String, String> statuses) {
        this.statuses = statuses;
    }

    public JobManagerBean getJobManager() {
        return jobManager;
    }

    public void setJobManager(JobManagerBean jobManager) {
        this.jobManager = jobManager;
    }

    public Date getDate1() {
        return date1;
    }

    public void setDate1(Date date1) {
        this.date1 = date1;
    }

    public Date getDate2() {
        return date2;
    }

    public void setDate2(Date date2) {
        this.date2 = date2;
    }

    public DeliveryOrder getDo1() {
        return do1;
    }

    public void setDo1(DeliveryOrder do1) {
        this.do1 = do1;
    }

    public DeliveryOrder getDo2() {
        return do2;
    }

    public void setDo2(DeliveryOrder do2) {
        this.do2 = do2;
    }
    
    // send email , edited by zy Nov 9
    public String sendSalesOrderToCustomer() {
        // edited by ZY, 9 Nov 2011
        String res = "so sent to supplier";
        String emailAddress = "";
        
        if (salesOrder == null || salesOrder.getCustomer() == null || salesOrder.getCustomer().getContactRecords() == null || salesOrder.getCustomer().getContactRecords().isEmpty()){
            res = "so is not able to sent to customer because no contact record is found.";
            System.out.println(res);
        } else {
            emailAddress = new ArrayList<ContactRecord>(salesOrder.getCustomer().getContactRecords()).get(0).getEmail();
            fileManagerBean.sendSalesOrder(emailAddress, salesOrder.getId());
            System.out.println("email address: "+emailAddress);
        }
        return null;
    }
    
    public boolean renderSendingButton() {
        if (salesOrder == null) {
            return false;
        } else {
            return salesOrder.getSalesOrderStatus().equals(Consts.ORDER_FULFILLING);
        }
    }
    
    public FileUploadManagerBean getFileManagerBean() {
        return fileManagerBean;
    }

    public void setFileManagerBean(FileUploadManagerBean fileManagerBean) {
        this.fileManagerBean = fileManagerBean;
    }
    
}
